<!-- csv 文件预览 -->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import codeContainer from './code-container.vue';
const props:any = defineProps({
  file: {
    required: true
  },
  languageType: {
    required: true,
    type: String
  }
})
const  text = ref('');
const errorText = ref('');
const csvtable = ref([]);
const  columns = ref([]);

async function queryFile(file) {
  try {
    const res = await file.text()
    text.value = res
    csv2array(res)
  } catch (error) {
    console.log('error', error)
    errorText.value = error
  }
}

// csv 转多维数组
function csv2array(csv) {
  const lines = csv.split('\n');
  const result = [];
  const headers = lines[0].split(',');
  for (let i = 1; i < lines.length; i++) {
      const obj = {};
      const currentline = lines[i].split(',');
      for (let j = 0; j < headers.length; j++) {
        obj[headers[j]] = currentline[j];
        if (j == headers.length - 1) {
          result.push(obj);
        }
      }
  }
  csvtable.value = result
  columns.value = headers.map(h => ({
    title: h,
    dataIndex: h,
    ellipsis: true,
    tooltip: true,
  }));
  console.log('headers', headers)
}

onMounted(() => {
  console.log(props);
  if (props?.file) {
    queryFile(props.file)
  }
})

</script>

<template>
  <div class="csv-container">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" title="Table">
        <a-table :columns="columns" :data="csvtable" />
      </a-tab-pane>
      <a-tab-pane key="2" title="csv 源码">
        <!-- <code>{{ text }}</code> -->
        <codeContainer :languageType="languageType" :file="props.file" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>


<style lang="scss">

.csv-container {
  height: 100%;
  width: 100%;
  margin: 0 auto;
  white-space: pre-wrap;
  word-break: break-all;
  overflow: auto;
  padding: 12px;
}
</style>
